package gormdb

import (
	"gitee.com/then-go-project/go-utils/base"
	"gorm.io/gorm"
)

type Pagination struct {
	PageParam
	Total     int64       `json:"total"`
	TotalPage int64       `json:"totalPage"`
	Dataset   interface{} `json:"dataset"`
}

type PageParam struct {
	Page     int         `json:"page"`
	PageSize int         `json:"pageSize"`
	Sort     []TableSort `json:"sort"`
}

type TableSort struct {
	Property  string `json:"property"`  //字段名称
	Direction string `json:"direction"` //排序描述ASC 正序；DESC 倒序
}

func Paginate(param PageParam, model interface{}, generateFindModel func(*gorm.DB) *gorm.DB) Pagination {
	baseDb := generateFindModel(base.GormDB)
	var count int64
	baseDb.Count(&count)

	dataSetDb := baseDb.Offset((param.Page - 1) * param.PageSize).Limit(param.PageSize)
	for _, sort := range param.Sort {
		dataSetDb = dataSetDb.Order(sort.Property + " " + sort.Direction)
	}

	//modelType := reflect.TypeOf(model)
	//modelSlice := reflect.MakeSlice(modelType, 0, 0)
	//dataSetDb.Find(&modelSlice)
	dataSetDb.Find(model)

	totalPage := count / int64(param.PageSize)
	if count%int64(param.PageSize) > 0 {
		totalPage++
	}

	return Pagination{
		PageParam: param,
		Total:     count,
		TotalPage: totalPage,
		Dataset:   model,
	}

}
